<?php
    /**
     * Created by PhpStorm.
     * User: huangzhongwei
     * Date: 2018/10/23
     * Time: 10:01
     */

    namespace app\api\controller;


    use app\api\validate\certification;
    use app\api\validate\ChangeRunningManState;
    use app\api\validate\IDMustBePositiveInt;
    use app\api\validate\IsMobile;
    use app\api\service\Account as AccountService;
    use app\api\validate\Login;
    use app\api\validate\PagingParameter;
    use app\common\model\Account as AccountModel;
    use app\api\validate\RegisterUser;
    use app\lib\exception\ExistingException;
    use app\lib\exception\MissException;
    use app\lib\exception\PasswordException;
    use app\lib\exception\SuccessMessage;
    use app\api\service\Token;
    use app\common\model\AccountHasVoucher;

    class Account extends BaseController
    {

        protected $beforeActionList = [
            'checkExclusiveScope' => ['only' => 'getverificationcode,registeruser,login,certification'],
            'checkSuperScope'     => ['only' => 'certificationpass'],
        ];


        /**
         * 用户发送短信验证码
         * @throws SuccessMessage
         * @throws \app\lib\exception\ParameterException
         * @throws \app\lib\exception\SmsException
         */
        public function getVerificationCode()
        {
            $validate = new IsMobile();
            $validate->goCheck();
            $data   = $validate->getDataByRule(input('post.'));
            $result = (new AccountService())->sendVerificationCode($data['telephone']);
            if ($result) {
                throw new  SuccessMessage();
            }
        }


        /**
         * 判断用户是否登陆
         * @return SuccessMessage
         * @throws ExistingException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function isRegistered()
        {
            $uid          = Token::getCurrentUid();
            $isExistPhone = (new AccountModel())->get($uid);

            return $isExistPhone;
        }


        /**
         * 注册手机号用户
         * @return SuccessMessage
         * @throws ExistingException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function registerUser()
        {

            (new RegisterUser())->goCheck();
            $data = input('post.');

            //检测验证码
            (new AccountService())->checkCaptcha($data['telephone'], $data['captcha']);
            $uid            = Token::getCurrentUid();
            $isExistPhone   = AccountModel::where('telephone', $data['telephone'])->find();
            $currentAccount = AccountModel::get($uid);
            if ($currentAccount['telephone']) {
                throw new ExistingException(['msg' => '当前用户手机已绑定', 'errorCode' => '10004']);
            }
            if ($isExistPhone) {
                throw new ExistingException(['msg' => '当前手机已存在', 'errorCode' => '10002']);
            }

            $data['password'] = setPassword($data['password']);
            (new AccountModel())->save($data, ['id' => $uid]);
            cache($data['telephone'], null);
            //新用户注册 返送优惠卷
            $accountHasVoucher = new AccountHasVoucher();
            $list              = [
                ['account_id' => $uid, 'voucher_id' => 8, 'expired_time' => strtotime("+28 days")],
                ['account_id' => $uid, 'voucher_id' => 9, 'expired_time' => strtotime("+28 days")],
                ['account_id' => $uid, 'voucher_id' => 10, 'expired_time' => strtotime("+28 days")],
                ['account_id' => $uid, 'voucher_id' => 11, 'expired_time' => strtotime("+28 days")],
                ['account_id' => $uid, 'voucher_id' => 12, 'expired_time' => strtotime("+28 days")],
                ['account_id' => $uid, 'voucher_id' => 13, 'expired_time' => strtotime("+28 days")],
            ];
            $accountHasVoucher->saveAll($list);
            return new SuccessMessage();
        }

        /**
         * 选择学生需要服务
         * 还是选择跑男需要接单
         *
         * @param $id
         *
         * @return SuccessMessage
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function selectRole($id)
        {
            (new IDMustBePositiveInt())->goCheck();
            $uid                          = Token::getCurrentUid();
            $currentAccount               = (new AccountModel())->field('is_logined,current_page,state')->get($uid);
            $currentAccount->current_page = $id;
            $currentAccount->save();
            return $currentAccount;
        }


        /**
         * 登陆
         * @return SuccessMessage
         * @throws MissException
         * @throws PasswordException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function login()
        {
            (new Login())->goCheck();
            $data = input('post.');
            //查找手机号是否存在
            $isExistPhone = AccountModel::where('telephone', $data['telephone'])->find();
            if (!$isExistPhone) {
                throw new MissException(['msg' => '手机号码不存在', 'errorCode' => '10003']);
            }

            if (setPassword($data['password']) != $isExistPhone['password']) {
                throw new PasswordException(['errorCode' => '10004']);
            }
            $isExistPhone->is_logined = 1;
            $isExistPhone->save();
            return new SuccessMessage();
        }

        /**
         * 忘记密码修改
         * @return SuccessMessage
         * @throws ExistingException
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function forgetPassword()
        {

            (new RegisterUser())->goCheck();
            $data = input('post.');
            //检测验证码
            (new AccountService())->checkCaptcha($data['telephone'], $data['captcha']);
            $uid            = Token::getCurrentUid();
            $currentAccount = AccountModel::get($uid);
            if ($currentAccount['telephone'] != $data['telephone']) {
                throw new ExistingException(['msg' => '当前用户手机错误', 'errorCode' => '10005']);
            }
            $data['password'] = setPassword($data['password']);
            (new AccountModel())->save($data, ['id' => $uid]);
            cache($data['telephone'], null);
            return new SuccessMessage();
        }


        /**
         * 跑男认证信息上传
         * @return SuccessMessage
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function certification()
        {
            (new certification())->goCheck();
            $data                          = input('post.');
            $uid                           = Token::getCurrentUid();
            $currentAccount                = AccountModel::get($uid);
            $currentAccount->is_runningman = 1;
            $currentAccount->state         = 1;
            $currentAccount->save($data);
            return $currentAccount;
        }


        /**
         * 跑男认证通过
         * @return SuccessMessage
         * @throws MissException
         * @throws \think\Exception\DbException
         */
        public function certificationPass()
        {
            (new IDMustBePositiveInt())->goCheck();
            $uid            = input('post.id');
            $currentAccount = AccountModel::where('is_runningman', 1)->get($uid);
            if (!$currentAccount) {
                throw new MissException(['msg' => '当前跑男不存在', 'errorCode' => 10006]);
            }
            $currentAccount->state = 1;
            $currentAccount->save();
            return new SuccessMessage();
        }

        /**
         * 获取用户信息
         * @return AccountModel|null
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function getAccountInfo()
        {

            $uid            = Token::getCurrentUid();
            $currentAccount = AccountModel::get($uid);
            return $currentAccount;

        }


        //管理后台获取所有用户
        public function getUsers($page = 1, $size = 30)
        {

            (new PagingParameter())->goCheck();
            $users = (new  AccountModel())->order('create_time', 'desc')->paginate(
                $size,
                false, [
                    'page' => $page,
                ]);

            if ($users->isEmpty()) {
                // 对于分页最好不要抛出MissException，客户端并不好处理
                return [
                    'current_page' => $users->currentPage(),
                    'data'         => [],
                ];
            }
            $data = $users->toArray();
            return [
                'current_page' => $users->currentPage(),
                'data'         => $data,
            ];
        }

        /**
         * 获取所有跑男
         *
         * @param int $page
         * @param int $size
         *
         * @return array
         * @throws \app\lib\exception\ParameterException
         */
        public function getRunningman($page = 1, $size = 30)
        {
            (new PagingParameter())->goCheck();
            $runningman = AccountModel::getRunningman($page, $size);
            if ($runningman->isEmpty()) {
                // 对于分页最好不要抛出MissException，客户端并不好处理
                return [
                    'current_page' => $runningman->currentPage(),
                    'data'         => [],
                ];
            }
            $data = $runningman->toArray();
            return [
                'current_page' => $runningman->currentPage(),
                'data'         => $data,
            ];
        }


        /**
         * 跑男认证 审核
         * @return SuccessMessage
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function changeState()
        {
            (new ChangeRunningManState())->goCheck();
            $id      = input('post.id');
            $state   = input('post.state');
            $account = (new AccountModel())->get($id);
            if (!$account) {
                throw new MissException(['msg' => '用户不存在', 'errorCode' => 10006]);
            }

            $account->state = $state;

            $account->save();
            return new SuccessMessage();
        }


        /**
         * 保存用户信息
         * @return SuccessMessage
         * @throws MissException
         * @throws \app\lib\exception\ParameterException
         * @throws \think\Exception\DbException
         */
        public function saveWxUserInfo()
        {
            $uid = Token::getCurrentUid();

            $account = (new AccountModel())->get($uid);
            if (!$account) {
                throw new MissException(['msg' => '用户不存在', 'errorCode' => 10006]);
            }

            $data              = input('post.');
            $account->userinfo = $data;

            $account->save();
            return new SuccessMessage();
        }


        /**
         * 获取已注册用户数
         * @return array|\PDOStatement|string|\think\Collection
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function getAccountCount()
        {
            $account = (new AccountModel())->where('telephone', 'neq', "")->count();


            return $account;
        }

        /**
         * 获取跑男数
         * @return array|\PDOStatement|string|\think\Collection
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function getRunningManCount()
        {
            $account = (new AccountModel())->where([['telephone', 'neq', ""],['state','=',2],['is_runningman','=',1]])->count();

            return $account;

        }

    }
